package de.bib.dashboard.swing.chart;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.event.ChartChangeEvent;
import org.jfree.chart.event.ChartChangeListener;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

import javax.swing.*;

import java.awt.*;
import java.util.LinkedHashMap;
import java.util.Map;

public class ChartTools {
	private String title;
	private String horizontalLabel;
	private String verticalLabel;
	private Map<String, Number> mapParam;

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getHorizontalLabel() {
		return horizontalLabel;
	}

	public void setHorizontalLabel(String horizontalLabel) {
		this.horizontalLabel = horizontalLabel;
	}

	public String getVerticalLabel() {
		return verticalLabel;
	}

	public void setVerticalLabel(String verticalLabel) {
		this.verticalLabel = verticalLabel;
	}

	public Map<String, Number> getMapParam() {
		return mapParam;
	}

	public void setMapParam(Map<String, Number> mapParam) {
		this.mapParam = mapParam;
	}

	private CategoryDataset createDataset(Map<String, Number> paramData) {
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		for (Map.Entry<String, Number> entry : paramData.entrySet()) {
			dataset.addValue(entry.getValue(), verticalLabel, entry.getKey());
		}
		return dataset;
	}

	private ChartPanel createChart() {
		JFreeChart chart = ChartFactory.createBarChart(title, // chart title
				horizontalLabel, // yLabel
				verticalLabel, // xLabel
				createDataset(mapParam), // data
				PlotOrientation.VERTICAL, // orientation
				true, // include legend
				true, false);

		CategoryPlot cPlot = chart.getCategoryPlot();
		cPlot.setForegroundAlpha(0.5f);
		ChartPanel chartPanel = new ChartPanel(chart);
		chartPanel.setPreferredSize(new Dimension(500, 300));
		return chartPanel;
	}

	public static void main(String[] args) {
		ChartTools tools = new ChartTools();
		// create data
		Map<String, Number> mapParam = new LinkedHashMap<String, Number>();
		mapParam.put("IPhone", 25);
		mapParam.put("Android", 45);
		mapParam.put("Blackberry", 20);
		mapParam.put("Others", 5);

		tools.setMapParam(mapParam);
		tools.setTitle("Testing JFreechart");
		tools.setHorizontalLabel("Jenis Gadget");
		tools.setVerticalLabel("Pengguna");

		JFrame frame = new JFrame("Freechart Testing");
		frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		frame.setContentPane(tools.createChart());

		frame.pack();
		frame.setVisible(true);
	}

}
